// fs_wmall/paotui/pages/buy/buy.js
var a = getApp();
var base = require('../../../utils/lang.js');
const _ = base._
import authUser from '../../../utils/auth'
import {
	getDistance
} from '../../config.js'

import {
	pickerTap,
	bindMultiPickerColumnChange,
	loadData,
	loadHoursMinute,
	loadMinute,
	bindStartMultiPickerChange
} from '../../date.js'

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		content: '',
		startAddr: _('去哪里取'),
		endAddr: _('送哪里去'),
		tel: '',
		startDate: _("请选择日期"),
		multiArray: [
			[],
			[],
			[]
		],
		multiIndex: [0, 0, 0],
		weight: [],
		weight_index: 0,
		tip: [],
		tip_index: -1,
		isAgreement: true,
		money: '0.00',
		start_lat_lng: ['', ''],
		end_lat_lng: ['', ''],
		send_is_cumulate: "0",
		send_cumulate_price: "",
		send_cumulate_step: "",
		send_start_km: "",
		send_start_price: "",
	},
	pickerTap,
	bindMultiPickerColumnChange,
	loadData,
	loadHoursMinute,
	loadMinute,
	bindStartMultiPickerChange,
	submitFn() {
		const {
			isAgreement
		} = this.data
		if (!isAgreement) {
			wx.showToast({
				title: _('请勾选同意协议按钮'),
				icon: 'none'
			})
		} else {
			this.buyFn()
		}
	},
	agreementFn() {
		let {
			isAgreement
		} = this.data
		this.setData({
			isAgreement: !isAgreement
		})
	},
	telFn(e) {
		const {
			value
		} = e.detail
		this.setData({
			tel: value
		})
	},
	startFn() {
		wx.chooseLocation({
			success: res => {
				const {
					address,
					latitude,
					longitude
				} = res
				this.setData({
					start_lat_lng: [latitude, longitude],
					startAddr: address
				})
				this.compulatePrice()
			}
		})
	},
	endFn() {
		wx.chooseLocation({
			success: res => {
				const {
					address,
					latitude,
					longitude
				} = res
				this.setData({
					end_lat_lng: [latitude, longitude],
					endAddr: address
				})
				this.compulatePrice()
			}
		})
	},
	compulatePrice() {
		const {
			start_lat_lng,
			end_lat_lng,
			send_is_cumulate,
			send_cumulate_price,
			send_cumulate_step,
			send_start_km,
			send_start_price,
		} = this.data

		if (!send_is_cumulate) return

		const lat1 = start_lat_lng[0]
		const lng1 = start_lat_lng[1]
		const lat2 = end_lat_lng[0]
		const lng2 = end_lat_lng[1]

		if (lat1 === '' || lng1 === '' || lat2 === '' || lng2 === '') return

		const distance = getDistance(lat1, lng1, lat2, lng2)

		let money = ''

		if (distance * 1 <= send_start_km * 1) {
			// 距离小于起步距离,金额为起步价
			money = send_start_price
		} else {
			let beyondDistance = distance * 1 - send_start_km * 1
			money = send_start_price * 1 + Math.ceil(beyondDistance / send_cumulate_step) * send_cumulate_price
			this.setData({
				money
			})
		}

	},
	contentFn(e) {
		const {
			value
		} = e.detail
		this.setData({
			content: value
		})
	},
	bindWeightChange(e) {
		this.setData({
			weight_index: e.detail.value
		})
	},
	bindTipChange(e) {
		this.setData({
			tip_index: e.detail.value
		})
	},
	init() {
		a.util.request({
			'url': 'entry/wxapp/ErranderSend',
			success: res => {
				let {
					send_weight,
					send_tiplow,
					send_tipheight,
					send_premoney,
					send_is_cumulate,
					send_cumulate_price,
					send_cumulate_step,
					send_start_km,
					send_start_price,
				} = res.data
				send_weight = parseInt(send_weight)
				send_tiplow = parseInt(send_tiplow)
				send_tipheight = parseInt(send_tipheight)
				console.log('zcj')
				let weightArr = []
				for (var i = 1; i <= send_weight; i++) {
					let item = i + _('公斤内')
					weightArr.push(item)
				}
				let tipArr = []
				for (var i = send_tiplow; i <= send_tipheight; i++) {
					let item = i + _('元')
					tipArr.push(item)
				}

				send_is_cumulate = Boolean(send_is_cumulate * 1)

				let money = send_is_cumulate ? send_start_price : send_premoney

				this.setData({
					weight: weightArr,
					tip: tipArr,
					money: money,
					send_is_cumulate,
					send_cumulate_price,
					send_cumulate_step,
					send_start_km,
					send_start_price,
				})
			},
		})
	},
	buyFn() {
		const _openId = wx.getStorageSync('_openId')
		let {
			content,
			startAddr,
			endAddr,
			money,
			tel,
			startDate,
			weight,
			weight_index,
			tip,
			tip_index
		} = this.data
		let _tip = 0
		if (tip_index >= 0) {
			_tip = tip[tip_index]
		}
		if (startAddr === _('去哪里取')) {
			wx.showToast({
				title: _('请选择去哪里取'),
				icon: 'none'
			})
			return
		}
		if (endAddr === _('送哪里去')) {
			wx.showToast({
				title: _('请选择送哪里去'),
				icon: 'none'
			})
			return
		}
		if (tel === '') {
			wx.showToast({
				title: _('请填写电话'),
				icon: 'none'
			})
			return
		}
		if (startDate === _('请选择日期')) {
			wx.showToast({
				title: _('请选择日期'),
				icon: 'none'
			})
			return
		}
		let data = {
			type: 3,
			uid: _openId,
			content: content,
			start: startAddr,
			end: endAddr,
			money: money,
			tel: tel,
			date: startDate,
			weight: weight[weight_index],
			tip: _tip
		}
		a.util.request({
			'url': 'entry/wxapp/ErranderAddorder',
			data: data,
			success: res => {
				console.log('zcj')
				console.log(res)
				if (res.data.errcode === 0) {
					this.payFn(res.data)
				}
			},
		})
	},
	payFn(res) {
		wx.requestPayment({
			'timeStamp': res.data.timeStamp,
			'nonceStr': res.data.nonceStr,
			'package': res.data.package,
			'signType': res.data.signType,
			'paySign': res.data.paySign,
			'success': function(res) {
				console.log(res)
				wx.showToast({
					title: _('支付成功'),
				})
				setTimeout(function() {
					wx.redirectTo({
						url: '/fs_wmall/pages/wddd/order'
					})
				}, 1500)
			},
			'fail': function(res) {
				console.log(res)
				wx.showLoading({
					title: _('支付失败'),
				})
			}
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		let userInfo = wx.getStorageSync('userInfo') || "{}"
		userInfo = JSON.parse(userInfo)
		const redirect = '/fs_wmall/paotui/pages/fetch/fetch'
		if (!authUser(userInfo, redirect)) {
			return
		}
		this.init()
		const isWei = base.isWeiFn()
		this.setData({
			isWei,
			startAddr: _('去哪里取'),
			endAddr: _('送哪里去'),
			startDate: _("请选择日期"),
		})
		this.pickerTap()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		this.setData({
			_t: base._t()
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
